package com.liuhouse.service.impl;

import com.liuhouse.domain.LoginUser;
import com.liuhouse.pojo.User;
import com.liuhouse.service.SystemLoginService;
import com.liuhouse.utils.*;
import com.liuhouse.vo.BlogUserLoginVo;
import com.liuhouse.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class SystemLoginServiceImpl implements SystemLoginService {

    @Autowired
    //AuthenticationManager是security官方提供的接口
    private AuthenticationManager authenticationManager;

    @Autowired
    //RedisCache是我们在liuhouse-framework工程的config目录写的类
    private RedisCache redisCache;


    @Override
    public ResponseResult login(User user) {
        //封装登录的用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        //在下一行之前,封装的数据会先走UserDetailServiceImpl实现类,这个实现类我们的liuhouse-framework工程的service/impl目录里
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //上面那一行会得到所有的认证用户信息authenticate，然后下一行需要判断用户认证是否通过,如果authenticate的值是null，就说明认证没有通过
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或者密码错误");
        }
        //获取userid
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        //把这个userId通过我们写的JwtUtil工具类转成密文,这个密文就是token值
        String jwt = JwtUtil.createJWT(userId);
        //下面那行的第一个参数:把上面哪行的jwt,也就是token值保存到redis,存的时候是键值对的形式，值就是jwt,key要加上 bloglogin : 前缀
        //下面那行的第二个参数,要把哪个对象存入Redis,我们写的是loginUser，里面有权限信息,后面对用到
        redisCache.setCacheObject("login:"+userId , loginUser);
        HashMap<String, String> map = new HashMap<>();
        map.put("token" , jwt);
        //封装响应返回
        return ResponseResult.okResult(map);

    }


    //退出登录实现
    @Override
    public ResponseResult logout() {
        //获取当前登录用户的id
        Long userId = SecurityUtils.getUserId();
        //删除redis中对应的值 , 因为登录存入redis的时候 就是加上了  login  所以  这里子啊删除的时候也要加上login
        redisCache.deleteObject("login:"+userId);
        return ResponseResult.okResult();
    }
}
